<template>
  <div class="uesr">
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图 -->
    <el-card class="box-card">
      <el-row :gutter='20'>
       <el-col :span="12">
         <!-- 搜索 -->
          <el-input placeholder="请输入内容" v-model="query.query" clearable @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
       </el-col>
        <el-col :span="4">
          <el-button type='primary' @click="dialogVisible=true">添加用户</el-button>
       </el-col>
      </el-row>
    <!-- 列表 -->
       <el-table :data="userList" style="width: 100%" border stripe>
         <el-table-column type='index'></el-table-column>
         <el-table-column prop="username" label="姓名" width="180"></el-table-column>
         <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
         <el-table-column prop="mobile" label="电话"></el-table-column>
         <el-table-column prop="role_name" label="角色"></el-table-column>
         <el-table-column prop="role_name" label="状态">
           <template slot-scope="scope">
             <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
           </template>
         </el-table-column>
         <el-table-column label="操作" width="180">
           <!-- 插槽解决 -->
           <template slot-scope="scope">
             <!-- 修改 -->
             <el-button size='mini' type="primary" icon="el-icon-edit" @click="edituser(scope.row.id)"></el-button>
             <!-- 删除 -->
             <el-button size='mini' type="danger" icon="el-icon-delete" @click="del(scope.row.id)"></el-button>
             <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
        <el-button size='mini' type="warning" icon="el-icon-setting" @click="setrole(scope.row)"></el-button>
             </el-tooltip>
           </template>
         </el-table-column>
       </el-table>
       <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.pagenum" :page-sizes="[1, 5, 10, 20]" :page-size="query.pagesize"  layout="total, sizes, prev, pager, next, jumper" :total="total">
       </el-pagination>
    </el-card>
      <!-- 添加对话框 -->
       <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close='closedia'>
         <!-- 内容 -->
  
           <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="70px" >
              <el-form-item label="用户名" prop="username">
               <el-input v-model="addForm.username" ></el-input>
               </el-form-item>
           </el-form>
             <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="70px">
              <el-form-item label="密码" prop="password">
               <el-input v-model="addForm.password" ></el-input>
               </el-form-item>
            </el-form>
             <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="70px">
              <el-form-item label="邮箱" prop="email">
               <el-input v-model="addForm.email" ></el-input>
               </el-form-item>
            </el-form>
             <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="70px">
              <el-form-item label="手机" prop="mobile">
               <el-input v-model="addForm.mobile" ></el-input>
               </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
           <!-- 底部按钮 -->
            <el-button @click="dialogVisible = false">取 消</el-button>
           <el-button type="primary" @click="adduser">确 定</el-button>
           </span>
       </el-dialog>
       <!-- 修改用户对话框 -->
       <el-dialog title="修改用户" :visible.sync="editdialogVisible" width="50%" @close="editdialog">
         <el-form :model="editForm" :rules="editrules" ref="editForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名" >
              <el-input v-model="editForm.username" disabled></el-input>
             </el-form-item>
             </el-form>
            <el-form :model="editForm" :rules="editrules" ref="editForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
             </el-form-item>
             </el-form>
              <el-form :model="editForm" :rules="editrules" ref="editForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label='手机' prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
             </el-form-item>
             </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editdialogVisible= false">取 消</el-button>
             <el-button type="primary" @click="edituserinfo">确 定</el-button>
          </span>
      </el-dialog>
      <!-- 修改角色对话框 -->
      <el-dialog title="分配倔强" :visible.sync="roleVisible" width="50%" @close='clearselect'>
        <div>
          <p>当前的用户:{{userinfo.username}}</p>
          <p>当前的角色:{{userinfo.role_name}}</p>
          <p>分配新角色:  
            <el-select v-model="selectroleid" placeholder="请选择">
            <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
            </el-select>
            </p>
        </div>
        <span slot="footer" class="dialog-footer">
           <el-button @click="roleVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveNewRole">确 定</el-button>
        </span>
      </el-dialog >
  </div>
</template>

<script>
export default {
  data(){
    /* 自定义校验规则 */
    //验证邮箱
    var checkEmail=(rules,value,call)=>{
    const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          return call()
        }else{
          call(new Error('请输入正确的邮箱'))
        }
    }
    //验证手机
    var checkMobile=(rules,value,call)=>{
       const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          return call()
        }else{
          call(new Error('请输入正确的手机号'))
        }
    }
    return{
       selectroleid:'',
      query:{
        query:'',
        pagenum:1,
        pagesize:5
      },
      userList:[],
      total:0,
      currentPage:'',
      dialogVisible:false,//控制对话框的显示隐藏
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },//添加对
      rules:{
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
          ],
           password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15个字符', trigger: 'blur' }
          ],
         email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
             { validator:checkEmail,trigger:'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机', trigger: 'blur' },
            { validator:checkMobile,trigger:'blur' }
          ],
      },
      editdialogVisible:false,//修改
      //查询用户
      editForm:{},
      //修改规则
      editrules:{
         email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
             { validator:checkEmail,trigger:'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机', trigger: 'blur' },
            { validator:checkMobile,trigger:'blur' }
          ],
      },
      roleVisible:false,//角色对话框
      userinfo:{},//需要被分配角色的用户信息
      rolelist:[]//角色数据
    }
  },
  created(){
    this.getUserList()
  },
  methods:{
    getUserList(){
      this.$http.get('users',{params:this.query}).then(response =>{
        //console.log(response)
        let res = response.data
        if (res.meta.status!==200) return this.$message.error('失败')
          this.userList=res.data.users
          this.total=res.data.total
      })
    },
    /*  */
    handleSizeChange(size){
        console.log(size)
        this.query.pagesize=size
        this.getUserList()
    },
    /* 页码改变 */
    handleCurrentChange(page){
      console.log(page)
       this.query.pagenum=page
        this.getUserList()
    },
    /* 状态改变 */
     userStateChange(state){
       console.log(state)
       this.$http.put(`users/${state.id}/state/${state.mg_state}`).then(response =>{
         let res = response.data
         console.log(response)
         if (res.meta.status !== 200) {
           state.mg_state = !state.mg_state  //保证没有变化
           return this.$message.error('更新失败')
         }
         this.$message.success('更新成功')
         
       })
     },
     /* 对话框关闭 重制表单 */
      closedia(){
        this.$refs.ruleForm.resetFields()
      },
      //添加新用户 先验证
    adduser(){
     this.$refs.ruleForm.validate(valid => {
       if (!valid)return this.$message.error('校验失败')
       this.$http.post('users',this.addForm).then(response => {
         //console.log(response) 
         let res = response.data
         if (res.meta.status !== 201) return this.$message.error('添加失败')
           this.$message.success('添加成功')
           this.dialogVisible = false//隐藏对话框
           this.getUserList()//重新获取列表
         
       })
     })
    },
      /* 编辑用户 点击显示对话框 */
      edituser(id){
         this.editdialogVisible = true
         this.$http.get(`users/${id}`).then(response => {
           //console.log(response)
           let res = response.data
           if (res.meta.status !== 200)return this.$message.error('查询失败')
           this.editForm = res.data
         }) 
      }  ,
      //修改对话框的显示
    editdialog(){
      this.$refs.editForm.resetFields()
      this.editdialogVisible = false
    },
      //修改用户 提交
      edituserinfo(){
        this.$refs.editForm.validate(valid => {
          if (!valid) return this.$message.error('修改校验失败')
          this.$http.put(`users/${this.editForm.id}`,{
           email: this.editForm.email,mobile:this.editForm.mobile
          }).then(response => {
           //console.log(response)
           let res = response.data
           if (res.meta.status !== 200)return this.$message.error('修改失败')
           this.editdialogVisible = false//关闭对话框
           this.getUserList()//更新用户列表
           this.$message.success('修改成功')//提示
         }) 
        })
      },
      /* 根据id删除 */
      del(id){ 
        //弹框
         this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { //返回的promise对象 返回confirm
          this.$http.delete(`users/${id}`).then(response => {
           //console.log(response)
           let res = response.data
           if (res.meta.status !== 200)return this.$message.error('删除失败')
              this.$message({
             type: 'success',
             message: '删除成功!'
          })
          this.getUserList()//更新用户列表
        })
        }).catch(() => {//取消的错误 返回cancel  
            this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        })
      },
       /* 分配角色 */
      setrole(userinfo){
        /* 先获取所有角色列表 作为下拉菜单 */
        this.$http.get(`roles`).then(response => {
           //console.log(response)
           let res = response.data
           if (res.meta.status !== 200)return this.$message.error('获取角色列表失败')
             this.rolelist = res.data
         }) 
         this.userinfo = userinfo
        this.roleVisible = true
      },
      /* 保存新角色 */
      saveNewRole(){
        if (!this.selectroleid) {
        return this.$message.error('qing分配角色')
  
       }
       this.$http.put(`users/${this.userinfo.id}/role`,{rid:this.selectroleid}).then(response => {
           console.log(response)
           let res = response.data
           if (res.meta.status !== 200)return this.$message.error(res.meta.msg)
            this.$message.success('分配成功')
            this.getUserList()
            this.roleVisible = false
         }) 


      },
      /* 分配角色对话框的关闭 */
      clearselect(){
        this.userinfo = {}
        this.selectroleid = ''
      }


      },
}


</script>

<style lang="less" scoped>

</style>